const Koa = require('koa')
const { koaBody } = require('koa-body')
const error = require('koa-json-error')
const parameter = require('koa-parameter')
const mongoose = require('mongoose')
const path = require('path')
const app = new Koa()
const routing = require('./routes')
const { connectionStr } = require('./config')
async function connectDatabase() {
  await mongoose.connect(connectionStr);
  console.log('连接成功')
}

connectDatabase().catch(err => console.log(err));

app.use(error({
  postFormat: (e, { stack, ...rest }) => process.env.NODE_ENV === 'production' ? rest : { stack, ...rest }
}))
app.use(koaBody({
  multipart: true, // 启用文件，支持文件格式
  formidable: {
    uploadDir: path.join(__dirname, '/public/uploads'), // 设置上传目录
    keepExtensions: true // 保留扩展名
  }
}))
// 校验请求体
app.use(parameter(app))

routing(app)

app.listen(3000, () => {
  console.log('程序启动在3000端口啦')
})